/**
 * @author jouyang
 */
var QS_FundChartComponent = function(mainticker,reg,language){
	this._title = "Chart";
	this.timezone = "";
	this.securityType = [8]; // 8: mutural fund.
	this.autoTitle = true;
	
	//fixed: no intraday data,2011.8.22
    this.defaultFrequencyMenuCfg = {intraday:false,history:true,customer:true};
	this.requencyMenuCfg = {intraday:false,history:true,customer:true};
	
	this.dataUrl = {
        getTickerInfoURL :this.protocol+"qt.morningstar.com/switchservice/getids.ashx?" // get ticker information url.
    }
	//globalization parameters
    this.region = (reg==null?"USA":reg);
    this.lan = (language==null?"en_US":language);
    this.cur="USD";
	//corlors for line and fill.
    this.fillColors = typeof(QS_Style)!="undefined"?QS_Style.chart.fillColors:{pChart:"#c9d2dd",vChart:"#2f4880",sChart:"#d9dfeb"};
	this.colors={borderColor:null,gridColor:typeof(QS_Style)=="undefined"?"#dddddd":QS_Style.flot.grid.tickColor,lableFontColor:typeof(QS_Style)=="undefined"?"#545454":QS_Style.flot.grid.color};
	// control parameter.
    this.mainTicker = mainticker;
	this.tickerMaxNum = 7;  // the maximum compaire ticker in a chart.
    this.compairTickers =[];
	this.tickerInfos = {};
    this.mainTickerInfo = {type:"1",tenforeTicker:""} ;
    this.compairTickerInfo = [];
	this.events = {dividend:false};
	/*this.extendConfig = {
        indicators: {
			SMA:"",
            EMA: "",
            BBands: "",
            MACD: "",
            RSI: "",
            ROC: "",
            MAE: "",
            Momentum: "",
            WMA: ""
        }
    };*/
	this.latestTradeDate = new Date();
	this.endDate = new Date();
    this.startDate = this.endDate;
	
    this.zoomRange = 3;
    this.chartStyle = "mountain";
    this.frequency = "d";
    this.chartCursor = 1; // 0 Track boll; 1 Crosshair
    this.scaleType = 0; // 0 linear 1: log.
    this.yaxisAlign = "right";
    this.showGridLines  = true;
    
	 //slider control parameters
	this.isShowTimeSlider=true;
    this.pChartReady = false;
    this.sliderObj = null;
    this.slider_EndDate = this.latestTradeDate; //slider end date equal to last trade date.
    this.slider_StartDate = new Date(this.slider_EndDate.getFullYear()-2,this.slider_EndDate.getMonth(),this.slider_EndDate.getDate()) ;
    this.sDates={d:null,m:null};// the start date for daily data,weekly data.monthly data.
	this.rangSize = 512;  
    this.miniChartFrequency = "d";
    this.ichartSiwtchIndicatorWin = {flag:false,oldName:"",newName:"",data:null,ulelm:null};
	    // state parameters	
	this.scrollAble = false;
	this._selectedIndicatorName = ""; // it is for indicator input parameters window.		 
    this.isDrawing = false; // if or not on drawing.
	this.lock = false; // lock
	this.showNotes =false;
    this.timeout = null;
	this.mouseWheeTimeout = null;
    this.wheelNum = 0;
	this.simpleMenu=false;  // if or not show indicator menu in SR chart right menu.
    this.chartOffset = {left:0,top:0};
	this.hasConfirmBox = (typeof(Util) != "undefined" && typeof(Util.confirm) != "undefined") ? true:false;
	this.isShowLastLabel = true;
	this.selectionMode = {pan:true,zoomIn:false,zoomOut:false};
    this.zoomStack = [];
    // options for legend window
	this.legendInfo = {OHLC:false,Volume:false,showDateRangeString:true};
    // the size parameters for chart component.
	this.chartWidth = 760;
	this.outHeight = 0;
    this.pChartHeight = 300;
    this.vChartHeight = 60;
    this.miniChartHeight = 26;
    this.yLabelWidth = 50;
    this.minW = 300;  // the minimum of width of the chart component.
    this.minH = 100;  // the minimum of height of the chart component.
    this.iChartHeight = 80; // the height of legend is 20px and the height of mini-chart is 60px.
    // UI system configure
    this.UIConfig = {
		chartCtrl:"default",
		Chart:{
	       showTimeSlider:true
		},
		settingPanel:null,
		autoHeight:false,
		RightMenu:true,
		indicator:{},
		events:{},
		drawing:{},
		MouseWheel:true,
		ZoomIn:true
	};
	// UI Components
	this.uiComponents = {
		settingGroup:null,           // group menu in setting panel.
		ddlFrequency:null,			 // drop down list for frquency type.
		ddlZoom:null,                // drop down list for zoom type.
		ddlChartType:null,			// drop down list for chart type.
		ddlCursorType:null,         // drop down list for chart cursor.
		customDateB:null,         // customize date boxes.
		tabMenu: null,            // tab panel.
	 	chartTypeMenu: [],        // sub menus for tab menu items.
		tabZoomMenu:null,        // zoom menu in tab panel.
		rightMenu:null,          // right menu for price chart.
		indexScrollPN:null,
		miniChartRightMenu:{}    // right menu for mini-chart (indicator and valuation chart). {menu: menu object,owner:the mini-chart value}
	};
	this._contains = {         
		pChartContainer:null,      // for price chart.
		mChartContainer:null,		// for silder chart
		toolContainer : null,      // for right menu.
		$settingPanel : null       // for setting Panel.
	};
	this._elements = {
		legendElm:null,
		crosshairLegendElm:null,
		crosshairLegendWin:null,
		lineXElm:null,
		lineYElm:null,
		xLabelElm:null,
		addCompairBtElm:null,
		indicatorWinElm:null,
		eventULElm:null,
		valuationULElm:null,
		indicatorULElm:null,
		chkLock:null,
		growthMenu:null,
		oscIndicatorMenu:null,
		tabmenuZoomEl:null,
		$ddlZoom:null, 
		$ddlFrequency:null, 
		$ddlChartType:null, 
		$ddlCursorType:null,
		$customDate:null,
		$ratioScale:null,
		$drawBlock:null,
		$yaxisAlign:null,
		zoomMask:null
	}
	this.iChartContainers = {};    //new chart contains 
	 // the flot object parameter.
    this.pFlot = null; // price chart
    this.mFlot = null; // slider chart.
    this.iFlots = {MACD:null,RSI:null,ROC:null,Momentum:null,Mass:null,ForceIndex:null};
	 // chart data
	this.chartData ={
		DataList:[],
		eventDataList:null,
		eventInfoList:null,
		MiniChartData: []
		};
	this.iChartData = {MACD:[],RSI:[],ROC:[],Momentum:[],WMA:[],Mass:[],ForceIndex:[]};
		// maps
	this._securityTypeMap = {"ST":1,"FE":1,"XI":10,"FO":8,"FC":1};
	this._zoomIndexMap = {3:0,14:1,4:2,5:3,6:4,7:5,8:6,9:7,10:8,11:9};
	this._frequencyIndexMap = {minute:-4,minute5:-3,minute10:-2,minute15:-1,minute30:0,d:1,w:2,m:3};
	this._frequencyTxtMap = {minute:"1 "+QSLGTXT.shortminute,minute5:"5 "+QSLGTXT.shortminute,minute10:"10 "+QSLGTXT.shortminute,
        minute15:"15 "+QSLGTXT.shortminute,minute30:"30 "+QSLGTXT.shortminute,d:QSLGTXT.daily,w:QSLGTXT.weekly,m:QSLGTXT.monthly};
	this._frequencyMap={minute:1,minute5:5,minute10:10,minute15:15,minute30:30,d:"d",w:"w",m:"m"};
	this.tabMap =  ["mountain","growth"];
	this.tabIndexMap = {"mountain":0,"dot":0,"ab":0,"line":0,"growth":1,"growth10":1,"postTax":1};
		// data list for UI control components.
//	this.drawingData =[{val:"trendline",txt:"Trend Line"},{val:"rectangle",txt:"Rectangle"},
//		{val:"ellipse",txt:"Ellipse"},{val:"note",txt:"Note"},{val:"levelline",txt:"Level Line"},{val:"fibonacci",txt:"Fibonacci retracement levels"}];
	 // indicators parameters
    this.indicatorUI = {SMA:{title:QSLGIN.sma_t,parameter:[QSLGIN.sma_p1,QSLGIN.sma_p2,QSLGIN.sma_p3],defaultValue:[10,50,]},
		 EMA:{title:QSLGIN.ema_t,parameter:[QSLGIN.ema_p1,QSLGIN.ema_p2,QSLGIN.ema_p3],defaultValue:[10,,]},
		 BBands:{title:QSLGIN.bbands_t,parameter:[QSLGIN.bbands_p1,QSLGIN.bbands_p2],defaultValue:[20,2]},
         MACD:{title:QSLGIN.macd_t,parameter:[QSLGIN.macd_p1,QSLGIN.macd_p2,QSLGIN.macd_p3],defaultValue:[26,12,9]},
         RSI:{title:QSLGIN.rsi_t,parameter:[QSLGIN.rsi_p1],defaultValue:[14]},
         ROC:{title:QSLGIN.roc_t,parameter:[QSLGIN.roc_p1],defaultValue:[12]},
		 MAE: {title: QSLGIN.mae_t,parameter: [QSLGIN.mae_p1, QSLGIN.mae_p2],defaultValue: [14, 2]},
		 Momentum:{title:QSLGIN.momentum_t,parameter:[QSLGIN.momentum_p1],defaultValue:[2]},
		 WMA:{title:QSLGIN.wma_t,parameter: [QSLGIN.wma_p1],defaultValue: [15]}
   	};                                       
    this.indicatorsData = {SMA:{show:false,num:[null,null,null],colorIndex:[0,0,0],type:0},
		SMAV:{show:false,num:null,colorIndex:0,type:0},
		EMA:{show:false,num:[null,null,null],colorIndex:[0,0,0],type:0},
		BBands:{show:false,parameter:[10,2],colorIndex:0,type:0},
		MACD:{show:false,parameter:[26,12,9],type:1,mty:1},
		RSI:{show:false,parameter:[14],type:1,mty:2},
		ROC:{show:false,parameter:[12],type:1,mty:1},
		MAE:{show:false,parameter:[14,2],type:0},
		Momentum:{show:false,parameter:[2],type:1,mty:1},
		WMA:{show:false,parameter:[15],type:0,mty:0}
 	};
	this.eventsData = [{
        txt: QSLGTXT.dividend,
        val: "dividend",
        name: "dividends",
        type: "checkbox",
        checked: false
    }];
    this.dailyFreMenuData=[{txt:QSLGTXT.daily,val:"d",type: "ratio"},{txt:QSLGTXT.weekly,val:"w",type: "ratio"},
        {txt:QSLGTXT.monthly,val:"m",type: "ratio"}];
    this.weeklyFreMenuData=[{txt:QSLGTXT.weekly,val:"w",type: "ratio"},{txt:QSLGTXT.monthly,val:"m",type: "ratio"}];
    this.monthlyFreMenuData = [{txt:QSLGTXT.monthly,val:"m",type: "ratio"}];
	this.zoomListData =  [{txt:"1 "+QSLGTXT.shortmonth,val:"3",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
		{txt:"2 "+QSLGTXT.shortmonth,val:"14",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
		{txt:"3 "+QSLGTXT.shortmonth,val:"4",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
        {txt:QSLGTXT.ytd,val:"5",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
		{txt:"1 "+QSLGTXT.shortyear,val:"6",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
		{txt:"3 "+QSLGTXT.shortyear,val:"7",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
		{txt:"5 "+QSLGTXT.shortyear,val:"8",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
		{txt:"10 "+QSLGTXT.shortyear,val:"9",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
		{txt:QSLGTXT.max,val:"10",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.monthlyFreMenuData},
		{txt:QSLGTXT.custom,val:"11",type: "ratio"}];
	this.frequencyListData = [{txt:QSLGTXT.daily,val:"d"},{txt:QSLGTXT.weekly,val:"w"},{txt:QSLGTXT.monthly,val:"m"}];
	this.cursorTypeListData = [{txt:QSLGTXT.trackball,val:"0",type: "ratio"},{txt:QSLGTXT.crosshair,val:"1",type: "ratio"},
	   {txt:QSLGTXT.off,val:"3",type: "ratio"}];
	this.chartTypeListData = [{txt:QSLGTXT.mountain,val:"mountain",type: "ratio"},{txt:QSLGTXT.line,val:"line",type: "ratio"},
		{txt:QSLGTXT.dot,val:"dot",type: "ratio"},{txt:QSLGTXT.abovebelow,val:"ab",type: "ratio"},
		{txt:QSLGTXT.pergrowth,val:"growth",type: "ratio"},{txt:QSLGTXT.tenkgrowth,val:"growth10",type: "ratio"},{txt:QSLGTXT.posttaxreturn,type:"ratio",val:"postTax"}];
	this.scaleTypeListData = [{txt:QSLGTXT.linear,val:"0"},{txt: QSLGTXT.logarithmic,val:"1"}];
    this.yaxisAlignListData=[{txt: QSLGTXT.left,val:"left"},{txt:QSLGTXT.right,val:"right"}];
	this.selectionModeListData=[{txt: QSLGTXT.pan,val:"pan"},{txt: QSLGTXT.zoomin,val:"zoomin"},{txt: QSLGTXT.reset,val:"reset"}];
	this.tabList=[{txt:QSLGTXT.line,id:0,closable:false},{txt:QSLGTXT.growth,id:1,closable:false}];
	this.chartTypeMenuData=[[{txt:QSLGTXT.mountain,type:"ratio",val:"mountain"},
		{txt:QSLGTXT.line,type:"ratio",val:"line"},{txt:QSLGTXT.dot,type:"ratio",val:"dot"},{txt:QSLGTXT.abovebelow,type:"ratio",val:"ab"}],
		[{txt:QSLGTXT.pergrowth,type:"ratio",val:"growth"},
		{txt:QSLGTXT.tenkgrowth,type:"ratio",val:"growth10"},{txt:QSLGTXT.posttaxreturn,type:"ratio",val:"postTax"}]];
	this.settingGroupList = [{name: QSLGTXT.display,id: 1},{name: QSLGTXT.window,id: 6}, {name: QSLGTXT.compare,id: 2,closable: false},
	 	{name: QSLGTXT.drawingandnotes,id: 3},{name: QSLGTXT.indicators,id: 4},{name: QSLGTXT.events,id: 5}];
	this.indicatorTabList=[{txt:QSLGTXT.popular,id:0,closable:false},
		{txt:QSLGTXT.pricetrends,id:2,closable:false},{txt:QSLGTXT.oscillator,id:3,closable:false}];
	this.indicatorPanelData=[[{txt:QSLGIN.bbands_name,val:"BBands",type: ""},{txt:QSLGIN.macd_name,val:"MACD",type: ""},
		{txt:QSLGIN.roc_name,val:"ROC",type: ""},
		{txt:QSLGIN.rsi_name,val:"RSI",type: ""},{txt: QSLGIN.sma_name,val: "SMA",type: ""}],
		[{txt:QSLGIN.bbands_name,val:"BBands",type: ""},{txt:QSLGIN.ema_name,val:"EMA",type: ""},
		 {txt:QSLGIN.mae_name,val:"MAE",type: ""},{txt:QSLGIN.macd_name,val:"MACD",type: ""},
		 {txt:QSLGIN.momentum_name,val:"Momentum",type: ""},{txt:QSLGIN.roc_name,val:"ROC",type: ""},
		 {txt: QSLGIN.sma_name,val: "SMA",type: ""},{txt: QSLGIN.wma_name,val: "WMA",type: ""}],//,{txt: "Volatility-Fast",val: "FVolatility"}
		[{txt:QSLGIN.rsi_name,val:"RSI",type: ""}]
	 	];
	//min-chart right menu list data.
    this.indicatorL2Data=[{txt:QSLGTXT.pricetrends,selectable: false,val:"mainl2-pricetrend",subMenu:this.indicatorPanelData[1]},
		{txt:QSLGTXT.oscillator,val:"mainl2-oscillator",selectable: false,subMenu:this.indicatorPanelData[2]}];
	this.ichartMenuL1Data=[[],[]]; //min-chart right menu list data. one class.
    this.miniChartRightMenuData = [{
	        txt: "<b>"+QSLGTXT.indicators+"</b>",
	        val: "mini-indicator",
	        selectable: false
	    }, {
	        txt: "&nbsp;&nbsp;"+QSLGTXT.pricetrends,
	        val: "minil1-pricetrend",
	        selectable: false,
			hasSubMenu:true
	    }, {
	        txt: "&nbsp;&nbsp;"+QSLGTXT.oscillator,
	        val: "minil1-oscillator",
	        selectable: false,
			hasSubMenu:true
	    }, {
	        type: 'separator',
	        val: "s2"
	    }, {
	        txt: QSLGTXT.edit,
	        val: "edit"
	    }];
    this.rightMenuData = [{
	        txt: QSLGTXT.charttype,
	        val: "chartType",
	        type: "",
	        selectable: false,
	        subMenu: this.chartTypeListData
	    }, {
	        txt: QSLGTXT.chartcursor,
	        val: "cursorType",
	        type: "",
	        selectable: false,
	        subMenu: this.cursorTypeListData
	    }, {
	        txt: QSLGTXT.zoom,
	        val: "zoom",
	        type: "",
	        selectable: false,
	        subMenu: this.zoomListData
	    }, {
            txt: QSLGTXT.events,
            type: "",
            val: "event",
            selectable: false,
            subMenu: this.eventsData
        }, {
	        txt: QSLGTXT.indicators,
	        val: "indicator",
	        selectable: false,
	        subMenu: this.indicatorL2Data
	    }];	   
};
QS_FundChartComponent.prototype= $.extend({},QS_baseChart,{
	// initilize chart interfaces.
	initUIConfig:function(config) { // init the chart UI configuration.
        $.extend(this.UIConfig,config);
		/*for(var i in this.indicatorUI){
			if(!this.extendConfig.indicators.hasOwnProperty(i)){
				delete this.indicatorUI[i];
				delete this.indicatorsData[i];
			}
		}*/
        if (this.UIConfig.settingPanel != null) {
            this._contains.$settingPanel = $(this.UIConfig.settingPanel);
        }    
    },
	Init:function(outID,objname,config) {  // init
		if(typeof(this.id)=="undefined") {
			this.id = outID;
			if(typeof(GB_ChartDataManager)=="object") GB_ChartDataManager.subscribeChart(this);
		}
        this.objName = objname;
        this.outObj = $("#"+outID).addClass("rtc-chart-out");
        this.autoBoxID = outID+"_autoBox";
		//this._checkPermission();  // check permission.
        this.createChartUI();                      // create UI elements.
        this._initConfig(config);                  // init the user's configuration (chart state)
        this._createUiComponents();              // create Ui Components for chart.
		var t = [];
		if (typeof(this.mainTicker) != "undefined" && this.mainTicker != null && this.mainTicker != "") {
			t.push(this.mainTicker);
		}
		if(this.compairTickers && this.compairTickers.length > 0){
			t = t.concat(this.compairTickers);
		}
		if(t.length > 0){
			this.validateSavedTickers(t);
		}
    },
	initStartDate: function() {
		var y = this.latestTradeDate.getFullYear(), m = this.latestTradeDate.getMonth(), d = this.latestTradeDate.getDate();
		var d = GB_ChartDataManager.dates;
        this.sDates.d = d["d"];
		this.sDates.w = d["w"];
        this.sDates.m = new Date(1900,0,1);
        this.slider_StartDate = this.getSliderStartDate();  
    },
	_initConfig: function(cf)  { // init the chart's configuration
        if (cf == null || cf == "") {
            return;
        }
		if(cf.simpleMenu){  // if minichart for SR components.
			this.simpleMenu = true;
			this.rightMenuData.splice(4,1);
		}
		if (cf.chartStyle!=null){ 
			this.chartStyle = cf.chartStyle=="lines"?"mountain":cf.chartStyle;
			var hasStyle = false;
            for(var i = 0;i< this.chartTypeListData.length;i++){  //fix bug #1202 - david
                if(this.chartTypeListData[i].val == this.chartStyle){
                    hasStyle = true;
                    break;
                }
            }
            if(!hasStyle){
                this.chartStyle="mountain";
            }
		}
		if (cf.title)this._title = cf.title;
		
		////fixed: no intraday data,2011.8.22
		if(cf.requencyMenuCfg){
			this.requencyMenuCfg=cf.requencyMenuCfg;
		}
		
		if(cf.autoTitle!=null)this.autoTitle = cf.autoTitle;
        if (cf.mTicker != null) this.mainTicker = cf.mTicker; 
		if (cf.cTickers != null) this.compairTickers = cf.cTickers;
        if (cf.pWidth != null) this.chartWidth=cf.pWidth; 
        if (cf.pHeight != null) this.pChartHeight=cf.pHeight;
        if (cf.zRange != null) this.zoomRange = cf.zRange; 
		if (cf.startDate != null) this.startDate = RTQ_ChartUtil.convertToDate(cf.startDate);
        if (cf.endDate != null) this.endDate = RTQ_ChartUtil.convertToDate(cf.endDate);
		if (cf.region != null) this.region = cf.region;
        if (cf.lan != null) this.lan = cf.lan; 
		if (cf.cur != null) this.cur = cf.cur;
        if (cf.frequency != null) this.frequency = cf.frequency; 
        if (cf.slider_StartDate != null) this.slider_StartDate = RTQ_ChartUtil.convertToDate(cf.slider_StartDate);
        if (cf.miniChartFrequency != null) this.miniChartFrequency = cf.miniChartFrequency; 
		if (cf.events != null)$.extend(true,this.events,cf.events);
        //if (cf.showVolume != null) this.showVolume = cf.showVolume;
        if (cf.tickerInfos) this.tickerInfos = cf.tickerInfos;
        if (cf.chartCursor != null) this.chartCursor = cf.chartCursor;
		if (cf.lock!=null)this.lock = cf.lock;
		if (cf.showNotes!=null)this.showNotes = cf.showNotes;
		if(cf.yaxisAlign!=null){this.yaxisAlign=cf.yaxisAlign};
		if(cf.isShowTimeSlider!=null)this.isShowTimeSlider = cf.isShowTimeSlider;
		if(cf.scaleType)this.scaleType = cf.scaleType;
		if(cf.ticksize)this.ticksize = cf.ticksize;
		if(cf.Ticks)this.Ticks = cf.Ticks;
		if (cf.indicatorsData) { 
            for(var i in cf.indicatorsData){ // Fix bug#1199, remove the indeicators that MF can NOT support --- David 
                if(!this.indicatorsData[i]){
                    cf.indicatorsData[i] = null;
                    delete cf.indicatorsData[i];
                }
            }
			$.extend(true, this.indicatorsData, cf.indicatorsData);
		}
        if (cf.width != null) {
            this.chartWidth = (cf.width>this.minW)?cf.width:this.minW; 
        }
        if (cf.height != null) {
			if (this.UIConfig.chartCtrl == "rtqPanel") {
				this.outHeight = cf.height - 26;//window title=26 reduce window title.
			}else {
				this.outHeight = cf.height;
			}
			this._setSizeParas(this.chartWidth,this.outHeight);
        } 
		this.outObj.css({width:this.chartWidth+"px",height:this.outHeight+"px"});
        this._contains.pChartContainer.css({width:this.chartWidth+"px",height:this.pChartHeight+"px"});
		if(this._elements.zoomMask!=null)this._elements.zoomMask.css({height:this.pChartHeight+"px"});
        if(this._contains.mChartContainer!=null)this._contains.mChartContainer.css({width:this.chartWidth+"px",height:this.miniChartHeight+"px"});
    },
	saveConfig: function() {  // save the chart's configuration.
        var cf = {title:this._title,autoTitle:this.autoTitle,mTicker:this.mainTicker,cTickers:this.compairTickers,pWidth:this.chartWidth,pHeight:this.pChartHeight,
       	mHeight:this.miniChartHeight,events:this.events,
		zRange:this.zoomRange,startDate:RTQ_ChartUtil.formatDate(this.startDate),
        endDate:RTQ_ChartUtil.formatDate(this.endDate),region:this.region,lan:this.lan,cur:this.cur,frequency:this.frequency, 
        slider_StartDate:RTQ_ChartUtil.formatDate(this.slider_StartDate),
        miniChartFrequency:this.miniChartFrequency,chartStyle:this.chartStyle,
        tickerInfos:this.tickerInfos,chartCursor:this.chartCursor,scaleType:this.scaleType,yaxisAlign:this.yaxisAlign,
        ticksize:this.ticksize,Ticks:this.Ticks,lock:this.lock,showNotes:this.showNotes,isShowTimeSlider:this.isShowTimeSlider,/*fixed: no intraday data,2011.8.22*/requencyMenuCfg:this.requencyMenuCfg};
		var inds = {},vals={},indD = this.indicatorsData;
		for(var o in indD){
			if(indD[o].show){ // volume: default value is true.
				if(o == "SMA"||o == "SMAV"||o == "EMA"){
					inds[o]= {show:true,num:typeof(indD[o].num)=="object"?$.extend(true,[],indD[o].num):indD[o].num};
				}else{
					inds[o]= {show:indD[o].show,parameter:$.extend(true,[],indD[o].parameter)};
				}
			}
		}
		for(var o in this.valuations){
			if(this.valuations[o].show){
				vals[o]= {show:true};
			}
		}
		cf.indicatorsData=inds;
		cf.valuations=vals;
		return cf;
	},
	// generate UI elements and UI components.
	createChartUI:function() {
		var self = this,uc = this.UIConfig, el = this._elements, cons = this._contains,uiComps = this.uiComponents;
        uiComps.ddlChartType = uiComps.ddlFrequency = uiComps.ddlZoom = uiComps.ddlCursorType = null;	
        this.outObj.html(""); // clear html.
		if(uc.chartCtrl == "rtqPanel"){ // add tab panel
			this.outObj.append('<div class="rtc-ul-tab clearfix"><div class="rtc-tab-zoom">'+
				'<div class="rtq-ddl" style="z-index: 2000; width: 115px;"><div val="1" style="width: 111px;" class="rtq-ddl-ipt">'+
				'</div></div></div><div class="rtc-tab"></div></div>');
			el.tabmenuZoomEl = this.outObj.find(".rtc-tab-zoom .rtq-ddl");
		}
		var cc = $('<div class="rtc-chart-container rtc-price-chart"></div>').appendTo(this.outObj); // create price chart container.
		el.legendElm = $('<div class="rtc-legend-txt"></div>').appendTo(cc);  // add price chart legend
		cons.pChartContainer = $('<div class="rtc-chart rtc-chart-main"></div>').appendTo(cc);
		if(uc.ZoomIn){
            el.zoomMask = $('<div style="display:none" class="chart-zoom-mask"></div>').appendTo(cons.pChartContainer);
        }   
		// create crosshair hover window.
		el.crosshairLegendWin = $('<div class="rtc-legend-win" style="display:none;">'+
			'<div class="rtc-legend-win-wrap"></div></div>').appendTo(cons.pChartContainer);
		el.crosshairLegendElm = el.crosshairLegendWin.find(".rtc-legend-win-wrap");
        el.lineXElm = $('<div class="rtc-line-x"><span></span></div>').appendTo(cons.pChartContainer);
		el.lineYElm = $('<div class="rtc-line-y"></div>').appendTo(cons.pChartContainer);
		el.xLabelElm = el.lineXElm.find(":first-child");
		if(this.UIConfig.Chart.showTimeSlider){
			var mCon = $('<div class="rtc-chart-container"></div>').appendTo(this.outObj);
            cons.mChartContainer = $('<div class="rtc-chart"></div>').appendTo(mCon); 
		}else{
			this.isShowTimeSlider = false;
		}		  
        if (uc.chartCtrl == "rtqPanel") {
			this._createSettingPanelUI();			
		} else{
            el.indicatorULElm = this.outObj.find(".qs-indicator-list");
            el.$customDate = this.outObj.find(".customRange")
            el.eventULElm = this.outObj.find(".qs-event-list");
            el.valuationULElm = this.outObj.find(".qs-valuation-list");
            el.indexsULElm = this.outObj.find(".qs-index-list");
            el.relatedSecULElm = this.outObj.find(".qs-relative-list"); 
            el.tabmenuZoomEl = this.outObj.find(".rtc-tab-zoom .rtq-ddl");
        }
        if(typeof(this.afterCreateUI)=="function"){
            this.afterCreateUI();
        }
    },
	_createSettingPanelUI:function () {
		var el = this._elements,cons = this._contains,uiComps = this.uiComponents,self = this;
		cons.$settingPanel.html("");
		var settingGroup = new Util.GroupBox(cons.$settingPanel,this.settingGroupList,{width:180,groupBoxHeight:310,autoHeight:true});
		var gb1 = settingGroup.getGroup(1).bd, bHtml="";
        bHtml+='<div class="clearfix block-row-top"><h4>'+QSLGTXT.charttype+'</h4><div class="ddlChartType"></div></div>';
		bHtml+='<div class="clearfix block-row"><h4>'+QSLGTXT.verticalscale+'</h4><div class="ratioScale"></div></div>';
		bHtml+='<div class="clearfix block-row"><h4>'+QSLGTXT.yaxis+'</h4><div class="ratioYaxis"></div></div>';
		bHtml+='<div class="clearfix block-row"><h4>'+QSLGTXT.selectionmode+'</h4><div class="ratioSelectionMode"></div></div>';
		bHtml+='<div class="clearfix block-row"><h4>'+QSLGTXT.range+'</h4><div class = "customRange clearfix" ></div></div>';
		bHtml+='<div class="clearfix block-row"><div class="set-block"><h4>'+QSLGTXT.zoom+'</h4><div class="ddlZoom"></div></div>';
		bHtml+='<div class="set-block set-right"><h4>'+QSLGTXT.frequency+'</h4><div class="ddlFrequency"></div></div></div>';
		bHtml+='<div class="clearfix block-row"><div class="set-block"><h4>'+QSLGTXT.chartcursor+'</h4><div class="ddlCursorType"></div></div></div>';
    	gb1.append(bHtml);
		el.$customDate = gb1.find(".customRange");
		el.$ratioScale = gb1.find(".ratioScale");
		el.$yaxisAlign= gb1.find(".ratioYaxis");
		el.$selectionMode= gb1.find(".ratioSelectionMode");
		var str ="",cls;
        for(var i=0; i< this.scaleTypeListData.length;i++){
            cls = i==0?"rtq-ratio-left ":"rtq-ratio-off";
            str+='<a href="javascript:void(0)" catkey="scale" class="rtc-menu-trigger rtq-ratio '+cls+' " ';
            str+='value="'+ this.scaleTypeListData[i].val+'">'+this.scaleTypeListData[i].txt+'</a>';
        }
		el.$ratioScale.html(str);
		str ="";
		for(var i = 0;i<this.yaxisAlignListData.length;i++){
			str+='<a href="javascript:void(0)" catkey="yaxis" class="rtc-menu-trigger rtq-ratio '+(i==0?"rtq-ratio-left ":"rtq-ratio-off")+' " ';
			str+='value="'+ this.yaxisAlignListData[i].val+'">'+this.yaxisAlignListData[i].txt+'</a>';
		}
		el.$yaxisAlign.html(str);
		str ="";
		for(var i = 0;i<this.selectionModeListData.length;i++){
			str+='<a href="javascript:void(0)" catkey="selectionmode" class="rtc-menu-trigger rtq-ratio rtq-menu-selectmode '+(i==0?"rtq-ratio-left ":"rtq-ratio-off")+' '+(this.selectionModeListData[i].val!="reset"?" ":"rtq-ratio-chart-reset")+'" ';
			str+='value="'+ this.selectionModeListData[i].val+'">'+this.selectionModeListData[i].txt+'</a>';
		}
		el.$selectionMode.html(str);
		
		var gb2 = settingGroup.getGroup(2).bd;
		gb2.append('<div class="clearfix block-row-top"><h4>'+QSLGTXT.compare+'</h4><div class="clearfix" style="position:relative">'+
			'<input  id ="'+this.autoBoxID+'" class="qs-ui-ipt" type="text" style="width: 132px;" value="" />'+
			'<a href="javascript:void(0)" class="qs-ui-btn go qs-compare-button">ADD</a><div></div>');	
		//gb2.append('<div class="clearfix block-row"><h4>'+QSLGTXT.relatedindexes+'</h4><div class="relatedIndexs" style="height:80px"></div></div>')
		//gb2.append('<div class="clearfix block-row"><h4>'+QSLGTXT.relatedsecurities+'</h4><div class="relatedSecuities"></div></div>');
		el.addCompairBtElm = gb2.find(".qs-compare-button");	
		var gb2 = settingGroup.getGroup(3).bd;
		var gb2str = "<div class='clearfix block-row-top'><h4></h4>";
		for(var i =0;i<this.drawingData.length;i++){
			gb2str += "<div  catkey='draw' class='rtc-menu-trigger draw-row' value="+this.drawingData[i].val+">";
			gb2str += "<a href='javascript:void(0)'>"+this.drawingData[i].txt+"</a></div>";
		}
		gb2str+="</div>";
		gb2.append(gb2str);	
		el.$drawBlock = gb2.find(".block-row-top");
		var gb4 = settingGroup.getGroup(4).bd.addClass('rtq-chart-group-indi2');
		uiComps.indTabMenu = new Util.TabMenu(gb4[0],this.indicatorTabList, {
            	onActive: function(tab){}
        },{ 
           width:80,
           isExcuteCallbackAtInit:false,
		   autoFixtoText:false,
           vertical: true
        });
		var str="";
        for(var i=0;i<uiComps.indTabMenu.tabs.length;i++){
            str="";
            for(var o in this.indicatorPanelData[i]){
                var indo = this.indicatorPanelData[i][o];
                str+='<div class="check-row"><a href="javascript:void(0)" class="rtc-menu-trigger rtq-chkbox rtq-chkbox_off" ';
                str+=' value="'+indo.val+'" catkey="indicator" >'+indo.txt+'</a></div>';
            }
            uiComps.indTabMenu.tabs[i].panel.append(str);
        }   
		el.indicatorULElm = gb4.find(".rtq-tab-panels");
		gb4.css({position:"relative"}); 
		var gb5 =  settingGroup.getGroup(5).bd;
		var gb5str = "<div clearfix block-row-top><h4></h4><div class='event'>";
		for(var i = 0;i<this.eventsData.length;i++){
			var et = this.eventsData[i];
			gb5str += "<div class='check-row'><a class='rtc-menu-trigger rtq-chkbox rtq-chkbox_off' ";
			gb5str += "value='"+et.val+"' name='"+et.name+"' catkey='event' href='javascript:void(0)'>"+et.txt+"</a></div>";
		}
		gb5str +="</div></div>";
		gb5.append(gb5str);
		el.eventULElm = gb5.find(".event");
		var gb6 = settingGroup.getGroup(6).bd;
        uiComps.settingPlugin=new SettingPlugin(gb6,{className:'rtq-setting-plugin-black',width:170,showLockCheckable:false,showHideCheckable:false},{
            onChangeTitle:function(title,isAdd,isAuto){
                self.autoTitle = isAuto;
				self.onChangeTitle(title,isAdd,isAuto);
            }
        });
		gb6.append('<div class="clearfix block-row"><div class="set-block"><div class="lock"></div></div></div>');
        uiComps.chkLock = new Util.ButtonGroup(gb6.find('.lock'), [{
            txt: QSLGTXT.showtimerangeslider,
            val: 'showTimeSlider'
        }, {
            txt: QSLGTXT.lockondoubleclick,
            val: 'lock'
        }, {
            txt: QSLGTXT.shownotes,
            val: 'showNotes'
        }], {
            onClick: function(v, btn){
                if (v == "showTimeSlider") {
                    self.isShowTimeSlider = btn.isSelected;
                    if (self.isShowTimeSlider) {
                        cons.mChartContainer.show();
                    }
                    else {
                        cons.mChartContainer.hide();
                    }
                    self.changeOutSize(self.chartWidth, self.outHeight);
                }
                else if (v == "lock") {
                        self.lock = btn.isSelected;
                    }else if(v=="showNotes"){
				 		self.showNotes = btn.isSelected;
						if(self.showNotes){
							self._loadChartNote(self.mainTicker);
						}else{
							self._contains.pChartContainer.find(".qs-note-flot").remove();
						}
				 }
            }
        }, {
            type: 'checkbox',
            vertical: true
        });
        uiComps.chkLock.btns["lock"].el[0].title = 'This function allows you to prevent the window from updating' +
        ' when you double-click a security in the watchlist.';
    },
	_createUiComponents:function() {
		var uiComps = this.uiComponents, uc = this.UIConfig, cons = this._contains, el = this._elements,self = this;
		var objref,cls = "",hcolor="#FEFEFE";
		if (uc.chartCtrl == "rtqPanel") {
			objref = cons.$settingPanel;
			cls = "rtq-ddl-black", hcolor="#727272";
		} else {
			objref = this.outObj;
		}
		if(uc.chartCtrl == "rtqPanel"){  // create tab menu.
		    if (uiComps.ddlZoom == null) {
	            uiComps.ddlZoom = new Util.DropDownList(objref.find(".ddlZoom")[0],function(k,v){self.zoomSelected(k,v);},
	             self.zoomListData, {triggerByClick:false, width:76,disable:true,actionAtInit:false,className: cls});
	        }
	        if (uiComps.ddlFrequency == null) {
	            uiComps.ddlFrequency = new Util.DropDownList(objref.find(".ddlFrequency")[0], function(k,v){self.frequencySelected(k,v);},
	             self.frequencyListData, {triggerByClick:false, width:76,disable:true, actionAtInit:false,className: cls});
	        }
	        if (uiComps.ddlCursorType == null) {
	            var w = uc.chartCtrl=="default"?75:165;
	            uiComps.ddlCursorType = new Util.DropDownList(objref.find(".ddlCursorType")[0], function(k,v){self.cursorTypeSelected(k,v);},
	             self.cursorTypeListData, {triggerByClick:false, width:w,disable:true, actionAtInit:false,className: cls});
	        }
	        if (uiComps.ddlChartType == null) {
	            var w = uc.chartCtrl=="default"?105:165;
	            uiComps.ddlChartType = new Util.DropDownList(objref.find(".ddlChartType")[0], function(k,v){self.chartTypeSelected(k,v);},
	             self.chartTypeListData, {triggerByClick:false, width:w, disable:true,actionAtInit:false,className: cls});
	        }
			this._createTabMenu();
			this._createDateInputBoxes();    
		}
		this._createIndicatorInputWin(this.outObj); // create indicator input window.
		if (uc.RightMenu) {    // create right menu for price chart and mini-chart.
			this._createRightMenu(cons.pChartContainer);
			this._createIChartRightMenu();
		}
    } ,
	_setSizeParas: function(wd,hg){
		this.chartWidth = wd;
		this.outHeight = hg;
        var ih = this.getIChartsHeight();
        var h = hg-ih-25;  // slider chart :30px, subject chart legend height:25px.
        if (this.isShowTimeSlider) {
			h = h - 30;
		}
        if (this.UIConfig.chartCtrl == "rtqPanel") {
             h-=30;  // tab menu height.
        }
        var hh = h>this.minH?h:this.minH;
        this.pChartHeight = hh;
	},
	initComponent:function() { // init component state.
		var self = this;
        this._attachUIEvents();
        this._initUiComponentsStatus(); // init the status of UI controls.
        this.chartData.DataList = this.chartData.eventDataList = null;
        for(var o in this.iChartData){
			this.iChartData[o] = [];
		}
        this.initStartDate();
		if (typeof(this.setTitle)=="function") {
	        var t = this._getClientTicker(this.mainTicker);//this.tickerInfos[this.mainTicker]["ticker"];
	        this.setTitle(this._title,t);
	    }
        this.changeRange(this.zoomRange);
        setTimeout(function() {self.getSilderChartData();},200);
    },
	_initUiComponentsStatus: function() {  // initilize the status of UI  components.
	 	var el = this._elements, uiComps = this.uiComponents;
        if(uiComps.ddlZoom != null) uiComps.ddlZoom.setDisable(false);
        if(uiComps.ddlChartType != null) uiComps.ddlChartType.setDisable(false);
        if(uiComps.ddlCursorType!= null) uiComps.ddlCursorType.setDisable(false);
        if(uiComps.ddlFrequency != null) uiComps.ddlFrequency.setDisable(false);
		if(uiComps.settingPlugin!=null)uiComps.settingPlugin.setName(this.autoTitle,this.autoTitle?"":this._title);
        if (uiComps.rightMenu != null) {
            if(this.events.dividend) uiComps.rightMenu.changeUIState("dividend",null,true);
            //if(this.events.splits) uiComps.rightMenu.changeUIState("splits",null,true);
			//if(this.events.earnings) uiComps.rightMenu.changeUIState("earnings",null,true);
			uiComps.rightMenu.changeUIState(this.chartStyle,null,true);
			uiComps.rightMenu.changeUIState(this.chartCursor,null,true);
        }
        if(this.chartCursor != "1" && this.chartCursor != 1) {
            el.lineXElm.hide();
            el.lineYElm.hide();
        }
		if(this.isShowTimeSlider && uiComps.chkLock!=null){
			uiComps.chkLock.btns["showTimeSlider"].select();
		}
		if(this.lock == true && uiComps.chkLock!=null){
			uiComps.chkLock.btns['lock'].select();
		}
		if(this.showNotes == true && uiComps.chkLock!=null){
			uiComps.chkLock.btns['showNotes'].select();
		}
		if(this.yaxisAlign=="right"){
			if(el.$yaxisAlign!=null){
				el.$yaxisAlign.find("[value='left']").addClass("rtq-ratio-off");
                el.$yaxisAlign.find("[value='right']").removeClass("rtq-ratio-off");
			}
			el.xLabelElm.css({right:0,left:""});
		}else{
			if(el.$yaxisAlign!=null){
				el.$yaxisAlign.find("[value='right']").addClass("rtq-ratio-off");
                el.$yaxisAlign.find("[value='left']").removeClass("rtq-ratio-off");
			}
			el.xLabelElm.css({left:0,right:""});
		}
        if (uiComps.ddlZoom != null) {
			uiComps.ddlZoom.setTextValue(null, this.zoomRange);
		}
        if (uiComps.ddlFrequency != null) uiComps.ddlFrequency.setTextValue(null,this.frequency);
        if (uiComps.ddlCursorType != null) uiComps.ddlCursorType.setTextValue(null,this.chartCursor);
        if (uiComps.ddlChartType != null) uiComps.ddlChartType.setTextValue(null,this.chartStyle);
		if(this.scaleType == 1){  // change scale ratio state. 
			el.$ratioScale.find("[value='0']").addClass("rtq-ratio-off");
			el.$ratioScale.find("[value='1']").removeClass("rtq-ratio-off");
		}
		if (uiComps.tabMenu != null){
			var ing = this.tabIndexMap[this.chartStyle];
			uiComps.tabMenu.changeTabByIndex(ing,false);
		}
		for(var i = 0;i<this.chartTypeMenuData.length;i++){
			if(uiComps.chartTypeMenu[i]!=null && this.tabIndexMap[this.chartStyle]==i){  // select tab is growth.
				uiComps.chartTypeMenu[i].changeUIState(this.chartStyle,null,true);
			}
		}
        var obj = (this.UIConfig.chartCtrl == "default") ? this.outObj: el.eventULElm;
        if(this.events.dividend) obj.find("a[value='dividend']").removeClass("rtq-chkbox_off");
        //if(this.events.splits) obj.find("a[value='splits']").removeClass("rtq-chkbox_off");
		//if(this.events.earnings) obj.find("a[value='earnings']").removeClass("rtq-chkbox_off");
        for (var o in this.indicatorsData) {             // change indicator menu state.
            if (this.indicatorsData.hasOwnProperty(o) ) {
                 if (this.indicatorsData[o].show) {
                      el.indicatorULElm.find("a[value='"+o+"']").removeClass("rtq-chkbox_off");
                      if (this.UIConfig.RightMenu) {
                          if (o == "Volume") {
                              this.changeRightMenuClass(2, o, this.showVolume);
                              continue;
                          }
                          this.changeRightMenuClass(2, o, true);
                      }
                 }
            }
        }
		/*for(var o in this.valuations){
			if(this.valuations[o].show){
				el.valuationULElm.find("a[value='"+o+"']").removeClass("rtq-chkbox_off");
				if(this.UIConfig.RightMenu && this.valuations[o].hasOwnProperty("mty")){
					this.changeRightMenuClass(2, o, true);
				}else if(o=="FairValue"){
					this.changeRightMenuClass(2, o, true);
				}
			}
		}
		for(var i=0;i<this.compairTickers.length;i++){
			if(this.indexsMap[this.compairTickers[i]]){
				this.indexsMap[this.compairTickers[i]].show = true;
				el.indexsULElm.find("a[value='"+this.compairTickers[i]+"']").removeClass("rtq-chkbox_off");
			}
		}*/
    },
	_attachUIEvents: function () {  // bind events to price chart and volume chart legends.
		var el = this._elements, self = this, cons = this._contains;
		el.legendElm.unbind().bind("mouseover.rtqChart",function(e){  // mouse over price chart legend.
			var t = $(e.target);
			if (e.target.tagName.toUpperCase() == "SPAN"||t.hasClass("rtc-legend")) {
				var elm = t.closest(".rtc-legend");
				el.legendElm.find(".rtc-legend-remove").removeClass("rtc-legend-remove");
				if(elm.attr("name") != "MReturnIndex")elm.addClass("rtc-legend-remove"); // not dividend effect chart legend
			}else{
				el.legendElm.find(".rtc-legend-remove").removeClass("rtc-legend-remove");
			}
		}).bind("mouseout.rtqChart",function(e){                   // mouse out legend.
			el.legendElm.find(".rtc-legend-remove").removeClass("rtc-legend-remove");
		}).bind("click.rtqChart",function(e){
			var t = $(e.target);
			if (e.target.tagName.toUpperCase() == "SPAN"||t.hasClass("rtc-legend")) {
				var elm = $(e.target).closest(".rtc-legend");
				self.legendOnClick(elm);
			}
		});
		
		var $compare = $("#"+this.autoBoxID);
        if ($compare.length > 0) {  // init compair section   	
			if (typeof(GB_qsAutoCompleteBox) == "object") {
				GB_qsAutoCompleteBox.subscription(this.autoBoxID,function(line){			
					self.validateCompairTicker(line);
				},{needClear:true});
			}
			if (this.UIConfig.chartCtrl != "default") {
				$compare.css({color: "#DFDFDF"});
			}
            $compare.val("Enter Security").click(function(){self.clearBox(this);});
            if(el.addCompairBtElm!=null)el.addCompairBtElm.unbind("click").click( function(){          // add compare ticker button.
		        var tic = $("#"+self.autoBoxID).attr("value");
		        //if (tic != null && tic != "") {
					//self.validateCompairTicker(tic);
					GB_qsAutoCompleteBox.triggerACB(self.autoBoxID);
		       // }
			});
        }
		this.outObj.find(".rtc-menu-trigger").unbind("click").click(function(){  // bind events to list items.
            if(self.mainTicker!="" && self.mainTicker!=null){
				self.menuButtonClicked(this);
			} 
        });
		if(this.UIConfig.chartCtrl=="rtqPanel"){							// bind events to list items in setting panel.
	        cons.$settingPanel.find(".rtc-menu-trigger").unbind("click").click(function(){
				if(self.mainTicker!=""&& self.mainTicker!=null){
					self.menuButtonClicked(this);
				} 
	        });
		}
		this.attachMouseScoll();     
		this.attachZoomIn();         
    },
	clearBox:function(obj) {
	    if (obj == null) {
	        return;
	    }
	    var v=$(obj).val(); 
	    if(v.substring(0,4) == "Line" || v== "Enter Security") {
	        $(obj).val("");
			//$(obj).css("color","#333333");
	    }
		if(this.UIConfig.chartCtrl=="rtqPanel"){
			$(obj).css("color","#DFDFDF");
		}
    },
	getPChartData:function(successCallback){
		var self = this;
		this.pChartReady = false; // request chart data for price  chart.
		var option = [], ty = this.compairTickers.length > 0 ? "return":"price"; 
		if(this.chartStyle == "growth"||this.chartStyle=="growth10") ty = "return";
		if(this.chartStyle == "growth10"){
			ty+="_k";
		}
		var ls = {symbol:this.mainTicker,datapoints:{p:ty,indicators:[]}};
        if(this.chartStyle == "postTax"){
            ls = {symbol:this.mainTicker,datapoints:{postTax:"return",indicators:[]}};
        }
		if(this._frequencyIndexMap[this.frequency]>0){  // daiy, weekly, monthly.
			if(this.events.dividend ){
				ls.datapoints.ds= {isD: this.events.dividend };
			}
		}
		if(this.chartStyle == "growth10"){  // dividend effect chart.
			option.push(ls);
			if(this.chartStyle == "growth10"){
				if(this.compairTickers.length){
					for(var j = 0; j< this.compairTickers.length;j++){
						option.push({symbol:this.compairTickers[j],datapoints:{p:ty}});
					}
				}
			}
		}else{
			for(var o in this.indicatorsData){  // add overlayer chart data option.
				if(this.indicatorsData[o].type == 0){ 
					if(o=="EMA"||o=="SMA"){
						for(var i=0;i<this.indicatorsData[o].num.length;i++){
							if(this.indicatorsData[o].num[i]!=null){
								ls.datapoints.indicators.push({name:o,p:[this.indicatorsData[o].num[i]],vtype:ty});
							}
						}
					}else if(this.indicatorsData[o].show){  
						ls.datapoints.indicators.push({name:o,p:this.indicatorsData[o].parameter,vtype:ty});
					}
				}
			}
			option.push(ls);		
			if(this.compairTickers.length){
				for(var j = 0; j< this.compairTickers.length;j++){
					option.push({symbol:this.compairTickers[j],datapoints:{p:ty}});
				}
			}
		}	
		var stIndx = RTQ_ChartUtil.toDateIndex(this.startDate);
   		var endIndx = RTQ_ChartUtil.toDateIndex(this.endDate);
		if(this.UIConfig.chartCtrl=="rtqPanel"&&(typeof(this.showLoading) == 'function')) {// show loading img
			this.showLoading();
		}
		if(this._frequencyIndexMap[this.frequency]>0){  // historical
			GB_ChartDataManager.getHistoricalData(option,this._frequencyMap[this.frequency],stIndx,endIndx,function(data){
			self.pChartDataReady(data,successCallback)});
		}
	},
	getSilderChartData: function(){
		var dx=5, m = this.miniChartFrequency, startIndex=null, endIndex = null, self = this;
		if(this.miniChartFrequency == "minute"){
			dx = 1, m = "d";
			startIndex = RTQ_ChartUtil.toDateIndex(this.sDates.lMin), endIndex = RTQ_ChartUtil.toDateIndex(this.slider_EndDate);
		}
		var option = [{symbol:this.mainTicker,dx:dx,datapoints: {p:"price"}}];
		GB_ChartDataManager.getHistoricalData(option,m,startIndex,endIndex,function(data){
			self.sliderChartDataReady(data)		
		});
	},
	getIChartData: function(sName){
		var cd = this.chartData,self = this;
		if(this.iChartData[sName]||sName=="FairValue"||sName == "MReturnIndex"){
			var option;
			var stIndx = RTQ_ChartUtil.toDateIndex(this.startDate);
       		var endIndx = RTQ_ChartUtil.toDateIndex(this.endDate);
			if(this.indicatorsData[sName]||sName=="RDividend"||sName=="DYield"){
				var par = sName=="RDividend"||sName=="DYield"?[]:this.indicatorsData[sName].parameter;
				option =  [{symbol:this.mainTicker,datapoints: {indicators: [{name: sName,p: par,vtype:"price"}]}}];
				if(this._frequencyIndexMap[this.frequency]>0){  // historical
					GB_ChartDataManager.getHistoricalData(option,this._frequencyMap[this.frequency],stIndx,endIndx,function(data){
						self.iChartDataReady(data);
					});
				}
			}
		}
	},
	drawPChart:function() { // draw price chart.
		var cd = this.chartData, self = this, cons = this._contains, el = this._elements;
        if (cd.DataList == null || cd.DataList.length < 1) { 
            return;
        }
        this.mouseOutChart();
        if (this.zoomRange > 2) { // historical
            this.ticksize = null, this.Ticks = this.getTicks(cd.DataList[0].data,this.frequency);
        } 
        if (this.pFlot == null) { 
            this.pFlot = new mstar.flot(cons.pChartContainer,this.getChartOption("priceLine"));
			this.pFlot.setOption({imageHighlight:this.chartCursor==0});
            cons.pChartContainer.unbind("plothover").bind("plothover", function(event, pos, item){
									 		self.buildLegend(item,pos,false,false);
										});
            cons.pChartContainer.unbind("mouseout").bind("mouseout", function(e) { 
               var t = e.relatedTarget ? e.relatedTarget.nodeName.toLowerCase() : "";
			   if(Util.contains(cons.pChartContainer[0],e.relatedTarget)) return false;
			   else {
			   		if(self.timeout)clearTimeout(self.timeout);
			   		self.chartMouseOut();
			   }
			} );
            cons.pChartContainer.unbind("mouseover").bind("mouseover", function() {
				if(self.timeout)clearTimeout(self.timeout);
				self.chartOffset = cons.pChartContainer.offset();
				el.lineXElm.css({width:self.chartWidth});
				el.lineYElm.css({height:cons.pChartContainer.height()});
			} );
			cons.pChartContainer.unbind("drawEnd").bind("drawEnd",function(e,drawType){ 
				if (typeof(el.$drawBlock) != "undefined" && el.$drawBlock!=null && el.$drawBlock.length) {
					el.$drawBlock.find("[value='" + drawType + "']").removeClass("draw-row-select");
				}
				self.isDrawing = false;
				if(self.chartCursor==1){
					el.crosshairLegendWin.show();
				}
                if(typeof(self.afterDrawEnd)== "function"){
                    self.afterDrawEnd(drawType);
                }
			});
        }
        var data = [];
        var w = 1, cloIndx;  // w is line width.
        for (var i = 0; i < cd.DataList.length; i++) { 
            w = i == 0?2:1;
			cloIndx = cd.DataList[i].colorIndex == null ?i:cd.DataList[i].colorIndex;
			var sty = "line";
            if (i == 0) {   // subject ticker.
            	var sy = this.chartStyle;
				sty = sy == "mountain"||sy=="growth"||sy=="growth10"||sy=="dEffect"||sy=="postTax"?"mountain":this.chartStyle;
            }
			data.push(this.getChartData(cd.DataList[i].data,sty,1,cloIndx,w));
        }
        if (this.zoomRange > 2&&this._frequencyIndexMap[this.frequency]>0 &&
			(this.events.dividend || this.events.splits||this.events.earnings) &&
			 cd.eventDataList != null && cd.eventDataList.length > 0) {  //historical data;
             data.push(this.getChartData(cd.eventDataList,"img",1,null)); 
        }
		var cs = this.chartStyle;
		var scal = (this.scaleType == "1" && (this.compairTickers.length > 0||cs=="growth"||cs=="dEffect"))?0: parseInt(this.scaleType,10);
		var drawingAble = true,unit = cs=="growth10"?"k":"";;
		if(cs=="mountain"||cs=="line"||cs=="dot"||cs=="ab"||cs=="growth"||cs=="growth10"||cs=="dEffect"){
			var ct = (cs=="growth"||cs=="growth10"||cs=="dEffect")?"mountain":cs;
			this.pFlot.setOption({xaxis:{tickSize:this.ticksize,ticks:this.Ticks,textAlign:this.xLabelAlign},
				lines:{lineType:ct},yaxis:{scaleType:scal},drawingAble:drawingAble});
		}else if(this.chartStyle=="ohlc"||this.chartStyle=="hlc"){
			 this.pFlot.setOption({xaxis:{tickSize:this.ticksize,ticks:this.Ticks,textAlign:this.xLabelAlign},
			 	OLHC:{olhcType:this.chartStyle},yaxis:{scaleType:scal},drawingAble:drawingAble});
		}else{
			 this.pFlot.setOption({xaxis:{tickSize:this.ticksize,ticks:this.Ticks,textAlign:this.xLabelAlign},
			 	yaxis:{scaleType:scal},drawingAble:drawingAble});
		}   
		this.pFlot.setOption({yaxis:{align:this.yaxisAlign,unit:unit},otherInfo:{ticker:this.mainTicker}});
        this.pFlot.init(data); 
        this.pChartReady = true;  
    },
	changeFrequencyStyle: function(num) {
        var uiComps = this.uiComponents, el = this._elements, f, mf ;
        mf = f = this.calculateFrequency(this.startDate);  
        this.changeFrequency(f);
		if (uiComps.rightMenu != null) { 
            uiComps.rightMenu.changeUIState(num,"zoom",true);
        }
		if(uiComps.tabZoomMenu !=null){
			uiComps.tabZoomMenu.changeUIState(num,null,true);
			el.tabmenuZoomEl.find(".rtq-ddl-ipt").html(this.zoomListData[this._zoomIndexMap[num]].txt+" | "+this._frequencyTxtMap[this.frequency]);
		}
        if (this._frequencyIndexMap[mf] > 0 && mf != this.miniChartFrequency) {  //slider chart view changed
            this.miniChartFrequency = mf;
			this.getSilderChartData();
        }else if(this._frequencyIndexMap[mf] <= 0&& this.miniChartFrequency != "minute"){//slider chart view changed
			this.miniChartFrequency = "minute";
			this.getSilderChartData();
		}else{
			this.setSliderHandleValues();
		}
    },
	changeFrequency: function(f) {
        if (this._frequencyIndexMap[f] > this._frequencyIndexMap[this.frequency]) {
			this.frequency = f;
		}// if can't exist frequency control element
        this.bindFrequencyMenu(f);
    },
	bindFrequencyMenu: function(f) {
        var st = this._frequencyIndexMap[f],uiComp = this.uiComponents, el = this._elements;
		if(st!= this.selectFreIndex){
			if(uiComp.ddlFrequency!=null){
				if(st==1){
	                uiComp.ddlFrequency.rebindData(this.dailyFreMenuData);
	            }else if(st==2){
	                uiComp.ddlFrequency.rebindData(this.weeklyFreMenuData);
	            } else if(st==3){
	                uiComp.ddlFrequency.rebindData(this.monthlyFreMenuData);
	            }
			}	
			this.selectFreIndex = st;
		}  
        if(uiComp.ddlFrequency != null) {
            uiComp.ddlFrequency.setTextValue("",this.frequency);
			if (uiComp.rightMenu != null) {
				uiComp.rightMenu.changeUIState(this.frequency,this.zoomRange,true);
			}
			if(uiComp.tabZoomMenu!=null){
				uiComp.tabZoomMenu.changeUIState(this.frequency,this.zoomRange,true);
				var ss = this.zoomListData[this._zoomIndexMap[this.zoomRange]].txt+" | "+this._frequencyTxtMap[this.frequency];
				el.tabmenuZoomEl.find(".rtq-ddl-ipt").html(ss);
			}
        }
    },
	calculateFrequency: function(startDate) {   // calculate frequency by range and start Date.
	   var f = "d";
	   if (startDate >= this.sDates.d) f = "d";
	   else if (startDate >= this.sDates.w) f = "w"; 
	   else f= "m" ;
       return f;
    },
	_upMiniFrequency: function() {  
        var f;
	    if (this.miniChartFrequency == "d") {
            f = "m";
        } else {
            f ="m";
        }
        return f;
    },
	drawSliderChart:function() {
		var  cons = this._contains;
		if(cons.mChartContainer==null)return false;
        if(this.mFlot == null) {
            this.mFlot = new mstar.flot(cons.mChartContainer,this.getChartOption("miniChart"));    
        }
        var ticks = this.chartData.MiniChartData.length?this.getTicks(this.chartData.MiniChartData[0],"d"):[];
		this.mFlot.setOption({xaxis:{tickSize:null,ticks:ticks}});
        this.mFlot.init(this.chartData.MiniChartData);
    },
	exportDataToExcel:function(){
		if(this.mainTicker==""||this.mainTicker==null)return;
		var symbols = [this.mainTicker],st = RTQ_ChartUtil.formatDate(this.startDate),ed = RTQ_ChartUtil.formatDate(this.endDate);
		if(this.compairTickers.length)symbols = symbols.concat(this.compairTickers)
		GB_ChartDataManager.exportDataToExcel(symbols,4,st,ed,this._frequencyMap[this.frequency],null);
	},
	fileMenuCallback:function(val){  // handler the file menu in windows click event.
		if(val=="export"){  // export data to excel.
			this.exportDataToExcel();
		}
	},
	refreshLastTradeDate:function(){
		
	}
	
});
